#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
验证导出的数据是否存在于数据库中
"""

from pymongo import MongoClient
from config import ROOM_MONGODB_CONFIG

def main():
    """验证导出的数据"""
    
    # 从CSV中读取的ID（前3条）
    test_ids = [
        "10000034_49564431",
        "10000034_49564448",
        "10000056_69607910"
    ]
    
    # 连接MongoDB
    print("\n正在连接MongoDB...")
    print(f"数据库: {ROOM_MONGODB_CONFIG['db_name']}")
    print(f"集合: {ROOM_MONGODB_CONFIG['collection_name']}")
    
    try:
        client = MongoClient(
            host=ROOM_MONGODB_CONFIG['host'],
            port=ROOM_MONGODB_CONFIG['port'],
            username=ROOM_MONGODB_CONFIG['username'],
            password=ROOM_MONGODB_CONFIG['password']
        )
        
        db = client[ROOM_MONGODB_CONFIG['db_name']]
        collection = db[ROOM_MONGODB_CONFIG['collection_name']]
        
        print("[OK] 数据库连接成功\n")
        
        # 查询集合统计
        total_count = collection.estimated_document_count()
        print(f"集合总文档数（估算）: {total_count}")
        
        # 获取前5条文档的_id
        print("\n前5条文档的_id:")
        for doc in collection.find().limit(5):
            print(f"  - {doc.get('_id')}")
        
        # 验证导出的ID
        print("\n验证导出的ID是否存在:")
        for test_id in test_ids:
            doc = collection.find_one({'_id': test_id})
            if doc:
                print(f"  [OK] {test_id} - 存在")
                print(f"       房型名称: {doc.get('roomName', 'N/A')}")
                print(f"       roomId: {doc.get('roomId', 'N/A')}")
            else:
                print(f"  [NOT FOUND] {test_id} - 不存在！")
        
        # 尝试按roomId查询
        print("\n按roomId查询（取自_id的后半部分）:")
        room_ids = ["49564431", "49564448", "69607910"]
        for room_id in room_ids:
            # 尝试多种查询方式
            count1 = collection.count_documents({'roomId': int(room_id)})
            count2 = collection.count_documents({'roomId': room_id})
            count3 = collection.count_documents({'rawData.roomID': int(room_id)})
            
            print(f"  roomId={room_id}")
            print(f"    - roomId (int): {count1} 条")
            print(f"    - roomId (str): {count2} 条")
            print(f"    - rawData.roomID (int): {count3} 条")
            
            if count1 > 0 or count2 > 0 or count3 > 0:
                # 找到一条来看看
                doc = collection.find_one({'$or': [
                    {'roomId': int(room_id)},
                    {'roomId': room_id},
                    {'rawData.roomID': int(room_id)}
                ]})
                if doc:
                    print(f"    [FOUND] _id: {doc.get('_id')}")
        
        client.close()
        print("\n" + "=" * 70)
        
    except Exception as e:
        print(f"[ERROR] 发生错误: {str(e)}")
        import traceback
        traceback.print_exc()

if __name__ == '__main__':
    main()

